<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="6" :xs="24">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>个人信息</span>
            </div>
          </template>
          <div>
            <div class="text-center">
              <el-avatar :size="100" :src="user.avatar" />
            </div>
            <ul class="list-group list-group-striped">
              <li class="list-group-item">
                <div class="item-label">用户名</div>
                <div class="item-content">{{ user.username }}</div>
              </li>
              <li class="list-group-item">
                <div class="item-label">昵称</div>
                <div class="item-content">{{ user.nickname }}</div>
              </li>
              <li class="list-group-item">
                <div class="item-label">手机号码</div>
                <div class="item-content">{{ user.phone }}</div>
              </li>
              <li class="list-group-item">
                <div class="item-label">邮箱</div>
                <div class="item-content">{{ user.email }}</div>
              </li>
              <li class="list-group-item">
                <div class="item-label">所属角色</div>
                <div class="item-content">{{ roleGroup }}</div>
              </li>
              <li class="list-group-item">
                <div class="item-label">创建日期</div>
                <div class="item-content">{{ user.createTime }}</div>
              </li>
            </ul>
          </div>
        </el-card>
      </el-col>
      <el-col :span="18" :xs="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>基本资料</span>
            </div>
          </template>
          <el-tabs v-model="activeTab">
            <el-tab-pane label="基本资料" name="userinfo">
              <el-form ref="userForm" :model="user" :rules="rules" label-width="80px">
                <el-form-item label="用户昵称" prop="nickname">
                  <el-input v-model="user.nickname" maxlength="30" />
                </el-form-item>
                <el-form-item label="手机号码" prop="phone">
                  <el-input v-model="user.phone" maxlength="11" />
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="user.email" maxlength="50" />
                </el-form-item>
                <el-form-item label="性别">
                  <el-radio-group v-model="user.sex">
                    <el-radio label="0">男</el-radio>
                    <el-radio label="1">女</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="submit">保存</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="修改密码" name="resetPwd">
              <el-form ref="pwdForm" :model="pwdForm" :rules="pwdRules" label-width="80px">
                <el-form-item label="旧密码" prop="oldPassword">
                  <el-input
                    v-model="pwdForm.oldPassword"
                    placeholder="请输入旧密码"
                    type="password"
                    show-password
                  />
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword">
                  <el-input
                    v-model="pwdForm.newPassword"
                    placeholder="请输入新密码"
                    type="password"
                    show-password
                  />
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                  <el-input
                    v-model="pwdForm.confirmPassword"
                    placeholder="请确认新密码"
                    type="password"
                    show-password
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="submitPwd">保存</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="修改头像" name="avatar">
              <el-upload
                class="avatar-uploader"
                action="/api/system/user/profile/avatar"
                :headers="headers"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="user.avatar" :src="user.avatar" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
              <div class="el-upload-text">上传头像</div>
              <div class="el-upload-tip">只能上传jpg/png文件，且不超过2MB</div>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getUser, updateUser, uploadAvatar } from '@/api/system/user'
import { getToken } from '@/utils/auth'
import { getInfo } from '@/api/auth'

const store = useStore()

// 选项卡默认激活
const activeTab = ref('userinfo')

// 用户信息表单引用
const userForm = ref(null)

// 密码表单引用
const pwdForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 用户信息
const user = reactive({
  username: '',
  nickname: '',
  phone: '',
  email: '',
  sex: '0',
  avatar: '',
  createTime: ''
})

// 角色组
const roleGroup = ref('')

// 上传头像的请求头
const headers = {
  Authorization: 'Bearer ' + getToken()
}

// 密码表单
// const pwdFormData = reactive({
//   oldPassword: '',
//   newPassword: '',
//   confirmPassword: ''
// })

// 表单校验规则
const rules = {
  nickname: [
    { required: true, message: '用户昵称不能为空', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '手机号码不能为空', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '邮箱地址不能为空', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 密码表单校验规则
const pwdRules = {
  oldPassword: [
    { required: true, message: '旧密码不能为空', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '新密码不能为空', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度必须在6到20个字符之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '确认密码不能为空', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== pwdForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 获取用户信息
const getUserProfile = () => {
  getInfo().then(response => {
    const data = response.data
    Object.assign(user, data)
    roleGroup.value = data.roles.join(',')
  })
}

// 提交表单
const submit = () => {
  userForm.value.validate(valid => {
    if (valid) {
      updateUser(user).then(() => {
        ElMessage.success('修改成功')
        // 更新Vuex中的用户信息
        store.dispatch('user/getInfo')
      })
    }
  })
}

// 提交密码表单
const submitPwd = () => {
  pwdForm.value.validate(valid => {
    if (valid) {
      updateUser(pwdForm.oldPassword, pwdForm.newPassword).then(() => {
        ElMessage.success('修改成功')
        // 清空表单
        pwdForm.oldPassword = ''
        pwdForm.newPassword = ''
        pwdForm.confirmPassword = ''
      })
    }
  })
}

// 头像上传成功处理
const handleAvatarSuccess = (response) => {
  if (response.code === 200) {
    user.avatar = response.data
    // 更新Vuex中的用户头像
    store.dispatch('user/getInfo')
    ElMessage.success('头像上传成功')
  } else {
    ElMessage.error(response.msg)
  }
}

// 头像上传前的校验
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是JPG或PNG格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过2MB!')
    return false
  }
  return true
}

onMounted(() => {
  getUserProfile()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.box-card {
  width: 100%;
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.text-center {
  text-align: center;
  margin-bottom: 20px;
}

.list-group {
  padding: 0;
  margin: 0;
}

.list-group-item {
  border-bottom: 1px solid #eee;
  padding: 10px 0;
  font-size: 14px;
  display: flex;
  justify-content: space-between;
}

.item-label {
  color: #999;
  width: 30%;
}

.item-content {
  color: #333;
  width: 70%;
  word-break: break-all;
}

.avatar-uploader {
  text-align: center;
  margin-bottom: 10px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.el-upload-text {
  color: #606266;
  font-size: 14px;
  text-align: center;
  margin: 10px 0;
}

.el-upload-tip {
  color: #909399;
  font-size: 12px;
  text-align: center;
}
</style>